package std.bank;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.Writer;
import java.net.Socket;
import java.net.UnknownHostException;

public class ClientStub
{
	private static final String CLRF = "\r\n";
	Socket socket;
	String httpversion = "HTTP/1.0";
	int objectNr;
	
	public ClientStub(Class<?>[] parameterTypes, Object[] parameterValues) throws UnknownHostException, IOException
	{
		socket = new Socket("localhost", 8080);
		Writer out = new PrintWriter(socket.getOutputStream(), true);
		BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
		
		if(parameterTypes.length == 0 & parameterValues.length == 0)
		{
			out.write("/bank/std.bank.BankImpl/:"+httpversion);
		}
		
		else if(parameterTypes.length == 2 & parameterValues.length == 2)
		{
			out.write("/bank/std.bank.AccountImpl/"
					+parameterTypes[0]+"="+parameterValues[0]+"&"
					+parameterTypes[1]+"="+parameterValues[1]+":"+httpversion);
		}
		
		String lastLine;
		String lines = null;
		while((lastLine = in.readLine()) != null)
		{
			lines += lastLine+" ";
		}
		if(lines.startsWith("200 All ok Content-Type: object "))
		{
			objectNr = Integer.parseInt(lines.substring(32));
		}
		else
		{
			System.out.println("Returned string mismatch");
		}
	}

	public Object performMethodCall(String methodName, Class<?>[] parameterTypes, Object[] parameterValues) 
	{
		try
		{
			Writer out = new PrintWriter(socket.getOutputStream(), true);
			out.write("/bank/std.bank.BankImpl/"+objectNr+"/"+methodName+"/");
			
			for(int i = 0; i < parameterTypes.length;)
				{
					if(i!=0)
					{
						out.write("&");
					}
					out.write(parameterTypes[i].getName()+"=");
					out.write(parameterValues[i]+"");
					i++;	
				}	
			out.write(httpversion);
		}
		catch(IOException e)
		{
			e.printStackTrace();
		}
		
		try 
		{
			BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
		
			String lastLine;
			String lines = null;
		
			while((lastLine = in.readLine()) != null)
			{
				lines += lastLine+" ";
			}
			if(lines.startsWith("200 All ok Content-Type: object "))
			{
				return lines.substring(32);
			}
			else
			{
				System.out.println("Returned string mismatch_");
			}
		}
		catch(IOException e)
		{
			e.printStackTrace();
		}
		return null;
	}
}
